<!-- 门店商品 -->
<template>
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <template #tableTitle>
      <a-dropdown v-if="checkedKeys.length > 0">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="ant-design:delete-outlined" />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button>批量操作
          <Icon icon="ant-design:down-outlined" />
        </a-button>
      </a-dropdown>
    </template>

    <template #logo="{ record }">
      <ImagePreview :image-list="[{src: record.logo, width: 60}]"/>
    </template>
  </BasicTable>
  <GoodsDrawer @register="registerDrawer" @success="handleSuccess" :showFooter="showFooter" />
</template>
<script lang="ts" name="shop-goods-category" setup>
import {onMounted, ref, unref} from 'vue';
import {Icon} from '/@/components/Icon';
import {ImagePreview} from '/@/components/Preview/index';
import {BasicColumn, BasicTable, useTable} from '/@/components/Table';
import {useDrawer} from '/@/components/Drawer';
import {render} from "/@/utils/common/renderUtils";
import GoodsDrawer from './GoodsDrawer.vue';
import {searchStoreGoodsFormSchema} from './goods.data';
import {listStore} from '../storeList/store.api';

import {
  batchDeleteFromCurrentStore,
  deleteFromCurrentStore,
  pageStoreGoods,
  updateStoreGoodsPublishStatus
} from './goods.api';
import {useRouter} from "vue-router"
import {useMessage} from '/@/hooks/web/useMessage';
import {useUserStore} from '/@/store/modules/user';

const { createMessage } = useMessage();
const router = useRouter()
const userStore = useUserStore()
const checkedKeys = ref<Array<string | number>>([]);
const showFooter = ref(true);
const [registerDrawer, { openDrawer }] = useDrawer();

const selectTenant = userStore.getSelectTenant
const tenantId = ref<any>()
const columns: BasicColumn[] = [
  {
    title: '商品名称',
    dataIndex: 'name',
    width: 200
  },
  {
    title: '类型',
    dataIndex: 'selectType',
    customRender: ({text}) => {
      return render.renderDict(text, 'spec_select_type')
    },
    width: 64,
  },
  {
    title: '商品分类',
    dataIndex: 'categoryName',
    customRender: ({text}) => {
      if (!text) {
        return ''
      }
      return render.renderTag(text.split(','), 'green')
    },
    width: 100,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 64,
  },
  {
    title: '销量',
    dataIndex: 'saleNumber',
    width: 100,
  },
  {
    title: '可用库存',
    dataIndex: 'saleNumber',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    customRender: ({text}) => {
      let color = 'green'
      if (text === '2') {
        color = 'red'
      }
      return render.renderTag(render.renderDict(text, 'goods_status'), color)
    },
    width: 64,
  },
];

const actionColumn: BasicColumn = {
  width: 150,
  title: '操作',
  dataIndex: 'action',
  fixed: 'right',
  slot: 'tableActions',
  actions:  (record: Recordable) => [
    {
      label: '删除',
      color: 'error',
      ifShow: !selectTenant.isMainTenant,
      popConfirm: {
        title: `是否确认删除 ${record.name}`,
        confirm: handleDelete.bind(null, record),
      },
    },
    {
      label: '编辑',
      ifShow: !selectTenant.isMainTenant,
      onClick: handleEdit.bind(null, record),
    },
  ],
  dropDownActions: (record: Recordable) => [
    {
      label: '上架',
      // auth: 'sys:area:save',
      ifShow: record.status === '2',
      onClick: handleUpdateGoodsPublishStatus.bind(null, record, true),
    }, 
    {
      label: '下架',
      // auth: 'sys:area:update',
      ifShow: record.status === '1',
      onClick: handleUpdateGoodsPublishStatus.bind(null, record, false),
    }
  ]
}


const [registerTable, { reload, getForm, expandCollapse }] = useTable({
  title: '商品规格列表',
  api: pageStoreGoods,
  formConfig: {
    baseColProps: { lg: 6, md: 12 },
    wrapperCol: { lg: 24, md: 24 },
    labelWidth: 90,
    schemas: searchStoreGoodsFormSchema,
    showResetButton: false,
  },
  beforeFetch: (params) => {
    params.tenantId = unref(tenantId.value)
  },
  clickToRowSelect: false,
  immediate: false,
  columns: columns,
  size: 'small',
  pagination: false,
  striped: true,
  useSearchForm: true,
  showTableSetting: false,
  bordered: false,
  showIndexColumn: false,
  tableSetting: { fullScreen: true },
  actionColumn
})

onMounted(() => {
  const { updateSchema } = getForm()
  const userStore = useUserStore()
  if (!userStore.getSelectTenant.isMainTenant) {
    reload()
    return
  }
  updateSchema({
    field: 'tenantId',
    componentProps: ({ formModel, formActionType }) => {
      return {
        optionFilterProp: "label",
        labelField: 'name',
        valueField: 'tenantId',
        showSearch: true,
        api: listStore,
        onSelect: async (value: any, option: any) => {
          console.log("option", option);
          tenantId.value = value
          reload()
        },
        onOptionsChange: async (options) => {
          if (options.length > 0) {
            formModel.tenantId = options[0].value
            tenantId.value = options[0].value
            console.log('tenantId', tenantId.value);
            reload()
          }
        }
      }
    },
  })
})

const rowSelection = {
  type: 'checkbox',
  columnWidth: 30,
  selectedRowKeys: checkedKeys,
  onChange: onSelectChange,
};

function onSelectChange(selectedRowKeys: (string | number)[]) {
  checkedKeys.value = selectedRowKeys;
}

async function handleUpdateGoodsPublishStatus(record, isPublish) {
  await updateStoreGoodsPublishStatus({ id: record.id, isPublish })
  createMessage.success(isPublish ? '上架成功' : '下架成功')
  reload()
}


function handleEdit(record) {
  showFooter.value = true;
  openDrawer(true, {
    record,
    isUpdate: true,
  });
}

async function handleDelete(record) {
  await deleteFromCurrentStore({ goodsIds: [record.id] }, () => {
    createMessage.success('删除成功')
    reload()
  })
}

async function batchHandleDelete() {
  await batchDeleteFromCurrentStore({ goodsIds: checkedKeys.value }, () => {
    createMessage.success('删除成功')
    reload()
  });
}

function handleSuccess() {
  reload();
}

</script>
